package com.example.mooctao.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mooctao.LoginForgetActivity;
import com.example.mooctao.R;
import com.example.mooctao.RegisterActivity;

import java.util.Objects;

//密码登录页面
public class PasswordFragment extends Fragment implements View.OnClickListener {
    private Button code;
    private EditText et_phone;
    private EditText et_password;
    private String mPassword;
    private String mPhone;
    private ActivityResultLauncher< Intent > register;
    private Button login1;
    private Button registe;
    //创建视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_password, container, false);
        code=v.findViewById(R.id.btn_forget);
        mPassword="123456";
        mPhone="12345678910";
        et_phone=v.findViewById(R.id.et_phone1);
        et_password=v.findViewById(R.id.et_password1);
        login1=v.findViewById(R.id.btn_login1);
        registe=v.findViewById(R.id.register_btn);
        login1.setOnClickListener(this);
        registe.setOnClickListener(this);
        code.setOnClickListener(this);
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone,11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
        //启动另外一个界面，并且接受其返回的结果，并保存
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                // 获取返回的数据
                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    if (intent.hasExtra("new_password")) {
                        mPassword = intent.getStringExtra("new_password");
                    }
                    if (intent.hasExtra("re_password")) {
                        mPassword = intent.getStringExtra("re_password");
                    }
                    if(intent.hasExtra("re_phone")){
                        mPhone=intent.getStringExtra("re_phone");;
                    }
                    if(intent.hasExtra("forget_phone")){
                        mPhone=intent.getStringExtra("forget_phone");
                    }
                }
            }
        });
        return v;
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            //点击忘记密码
            case R.id.btn_forget:
                // 启动 ForgetPasswordActivity
                Intent intent = new Intent(requireActivity(), LoginForgetActivity.class);
                register.launch(intent);
                break;
                //点击登录按钮
            case R.id.btn_login1:
                if(!Objects.equals(mPhone, et_phone.getText().toString())){
                    Toast.makeText(requireActivity(),"请输入正确的手机号",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!Objects.equals(mPassword, et_password.getText().toString())){
                        Toast.makeText(requireActivity(),"请输入正确的密码",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //提示用户登录成功
                    loginSuccess();
                break;
                //点击注册按钮
            case R.id.register_btn:
                Intent intent2=new Intent(requireActivity(), RegisterActivity.class);
                register.launch(intent2);
                break;

        }

    }
//提示登录成功信息
    private void loginSuccess() {
        String desc = String.format("您的手机号码是%s, 恭喜你通过登录验证，点击“确定”按钮返回上个页面", et_phone.getText().toString());

        // Create and show the success dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        builder.setTitle("登录成功")
                .setMessage(desc)
                .setPositiveButton("确定", (dialog, which) -> {
                    // End the current Activity (get the activity context)
                    requireActivity().finish();
                })
                .setNegativeButton("我再看看", null);

        AlertDialog dialog = builder.create();
        dialog.show();
    }
//文本输入键盘隐藏
    private class HideTextWatcher implements TextWatcher {
        private EditText mView;
        private int mMaxLength;
        private Context mContext;
        public HideTextWatcher(EditText v, int maxLength) {
            this.mView=v;
            this.mMaxLength=maxLength;
            this.mContext = requireActivity();  // 使用 requireActivity 获取上下文
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(editable.toString().length()==mMaxLength){
                //隐藏键盘
                InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null && mView != null) {
                    imm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
                }
            }

        }
    }
}
